package com.open.party.cloud.viewModel

import cn.android.x.inters.AndroidView
import cn.android.x.model.data.AppPageData
import cn.android.x.model.data.PageReq
import cn.android.x.model.data.ResultInfo
import com.open.party.cloud.ServerConfig
import com.open.party.cloud.model.ArticleEntity
import com.open.party.cloud.model.ArticleVo
import com.open.party.cloud.model.data.Api
import com.sinothk.android.utils.XUtils
import com.sinothk.rxretrofit.RxRetrofit
import org.greenrobot.eventbus.EventBus
import rx.Subscriber
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.util.ArrayList

class ArticlePresent(private val view: AndroidView<ResultInfo<AppPageData<ArticleEntity>>>) {

    /**
     * 获取文章列表
     */
    fun getArticleListData(pageReq: PageReq<ArticleVo>) {
        RxRetrofit.init(ServerConfig.SERVER_URL)
            .create(Api::class.java)
            .getArticleListData(pageReq)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Subscriber<ResultInfo<AppPageData<ArticleEntity>>>() {

                override fun onCompleted() {}

                override fun onError(e: Throwable) {
                    val result = ResultInfo<AppPageData<ArticleEntity>>(ResultInfo.ERROR, ResultInfo.getErrorMsg(e.message))
                    view.complete(result)
                }

                override fun onNext(result: ResultInfo<AppPageData<ArticleEntity>>) {
                    view.complete(result)
                }
            })
    }

    fun getArticleDetail(id: String) {
        RxRetrofit.init(ServerConfig.SERVER_URL, ServerConfig.getHeader())
            .create(Api::class.java)
            .getArticleDetail(id)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Subscriber<ResultInfo<ArticleEntity>>() {

                override fun onCompleted() {}

                override fun onError(e: Throwable) {
                    val res = ResultInfo<ArticleEntity>(ResultInfo.ERROR, ResultInfo.getErrorMsg(e.message))
                    res.eventType = "getArticleDetail"
                    EventBus.getDefault().post(res)
                }

                override fun onNext(result: ResultInfo<ArticleEntity>) {
                    result.eventType = "getArticleDetail"
                    EventBus.getDefault().post(result)
                }
            })
    }
}